package com.jiyun.filter;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String loginUrl ="/user/user/login";
        RequestPath path = exchange.getRequest().getPath();
        if(String.valueOf(path).equals(loginUrl)){
            return chain.filter(exchange);
        }
        if(String.valueOf(path).equals("/user/user/findByCourseId")){
            return chain.filter(exchange);
        }
        if(String.valueOf(path).equals("/user/user/findCourseAll")){
            return chain.filter(exchange);
        }
        if(String.valueOf(path).equals("/user/user/findLabels")){
            return chain.filter(exchange);
        }
        if(String.valueOf(path).equals("/user/user/userMenuAdd")){
            return chain.filter(exchange);
        }
        if(String.valueOf(path).equals("/user/answer/updateAnswer")){
            return chain.filter(exchange);
        }

        if(String.valueOf(path).equals("/user/user/findMenuAll")){
            return chain.filter(exchange);
        }
        if(String.valueOf(path).equals("/user/user/contest/findByAll")){
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("token");
        boolean verify = JWTUtil.verify(token, "123".getBytes());
        if(StringUtils.isBlank(token) || !verify){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
